package com.example.multithread.no1116;

import java.util.concurrent.Semaphore;

public class SemaphoreZeroEvenOdd {

    private int n;
    private Semaphore zero = new Semaphore(1);
    private Semaphore even = new Semaphore(0);
    private Semaphore odd = new Semaphore(0);

    public SemaphoreZeroEvenOdd(int n) {
        this.n = n;
    }

    public static void main(String[] args) {
        SemaphoreZeroEvenOdd zeroEvenOdd = new SemaphoreZeroEvenOdd(6);
        new Thread(() -> {
            try {
                zeroEvenOdd.zero();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                zeroEvenOdd.even();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                zeroEvenOdd.odd();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void zero() throws InterruptedException {

        for (int i = 0; i < n; i++) {
            zero.acquire();
            System.out.print(0);
            if(i%2 == 1){
                even.release();
            } else {
                odd.release();
            }
        }
    }

    /**
     * 偶数
     * @throws InterruptedException
     */
    public void even() throws InterruptedException {

        for (int i = 2; i <= n; i+=2) {
            even.acquire();
            System.out.print(i);
            zero.release();
        }
    }

    /**
     * 奇数
     * @throws InterruptedException
     */
    public void odd() throws InterruptedException {

        for (int i = 1; i <= n; i+=2) {
            odd.acquire();
            System.out.print(i);
            zero.release();
        }
    }
}
